package com.leetcode.algorithm.y22.m09.w3;

import com.leetcode.algorithm.common.TreeNode;

/**
 * 530. 二叉搜索树的最小绝对差
 * 
 * https://leetcode.cn/problems/minimum-absolute-difference-in-bst/
 * 
 * @author jie.deng
 *
 */
class Question0530Solution02 {

	public int getMinimumDifference(TreeNode root) {
		TreeNode[] prev = new TreeNode[] { null };
		int[] min = new int[] { Integer.MAX_VALUE };
		dfs(root, prev, min);
		return min[0];
	}

	private void dfs(TreeNode root, TreeNode[] prev, int[] min) {
		if (root == null) {
			return;
		}
		// 中序遍历
		dfs(root.left, prev, min);
		if (prev[0] != null && root.val - prev[0].val < min[0]) {
			min[0] = root.val - prev[0].val;
		}
		prev[0] = root;
		dfs(root.right, prev, min);
	}

}